package com.xo.xodemo.controller.process;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xo.xodemo.mapper.db1.*;
import com.xo.xodemo.model.*;
import com.xo.xodemo.service.FileService;
import com.xo.xodemo.springsecurityconfig.CustomUserDetails;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Controller
@RequestMapping("/process")
public class ComplaintController {
    @Autowired
    private ComplaintMapper complaintMapper;
    @Autowired
    private ProcessStatusMapper processStatusMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  ProcessSettingMapper processSettingMapper;
    @Autowired
    private  ProcessListMapper processListMapper;
    @Autowired
    private  HasBeenReadMapper hasBeenReadMapper;//未读消息
    private static SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    //转到投诉单申请界面
    @RequestMapping("/complaintpage")
    public String complaintpage(@AuthenticationPrincipal CustomUserDetails userDetails, Model model) throws IOException {

        //先生成一个流程
        String id=UUID.randomUUID().toString().toLowerCase();
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),14);
        ProcessEntity pet=new ProcessEntity();
        pet.setId(id);
        pet.setProcessType(14);
        pet.setAuditerStatus(1);
        pet.setApplyName(userDetails.getUsername());
        pet.setApplyRealName(userMapper.selectName(userDetails.getUsername()));
        pet.setAuditingCount(ps.getAuditingcount());
        pet.setAuditingPersonSetting(ps.getAuditingperson());
        pet.setDepartmentId(userDetails.getDepartmentId());

        model.addAttribute("id", id);  // 将id值添加到模型中
        model.addAttribute("userDetails", userDetails);  // 将完整的 userDetails 对象添加到模型中

        int auditerStatus = 1;
        pet.setAuditerStatus(auditerStatus);

        //添加审核人
        String[] ids = ps.getAuditingperson().split("\\|"); // 按照 "|" 分割字符串
        List<BaseUser> lbcopy = new ArrayList<>(); // 在循环外部初始化 lbcopy
        for (String idd : ids) {
            List<BaseUser> lb = userMapper.findBypositionId(idd);
            lbcopy.addAll(lb);
        }
        model.addAttribute("lb", lbcopy);

        processListMapper.insert(pet);
//        System.out.println(pet);

        return "process/complaint/complaintaddpage";
    }


    //转到投诉单修改申请界面
    @RequestMapping("/complaintupdate")
    public String complaintUpdate (@AuthenticationPrincipal CustomUserDetails userDetails,@RequestParam(value = "isauditing",defaultValue = "0") String isauditing,String id,Model model) throws IOException {
        //添加审核人
        ProcessSetting ps =processSettingMapper.selectbyidandtype(userDetails.getDepartmentId(),14);
        String[] ids = ps.getAuditingperson().split("\\|"); // 按照 "|" 分割字符串
        List<BaseUser> lbcopy = new ArrayList<>(); // 在循环外部初始化 lbcopy
        for (String idd : ids) {
            List<BaseUser> lb = userMapper.findBypositionId(idd);
            lbcopy.addAll(lb);
        }
        model.addAttribute("lb", lbcopy);
//        model.addAttribute("complaintEntity",complaintMapper.selectById(id));

        ComplaintEntity complaintEntity = complaintMapper.selectById(id);


//        // 寻找最后一组有数据的字段text与img
//        String text = null,img = null,textName,imgName;
//        try {
//            if (complaintEntity.getText1() == null && complaintEntity.getImg1() == null) {
//                // 如果text1和img1都为空，直接跳出循环
//                text = complaintEntity.getComplaintOpinions();
//                img = complaintEntity.getComplaintOpinionsFiles();
////                System.out.println("text1和img1都为空，直接跳出循环");
//            } else {
//                for (int groupIndexone = 1; groupIndexone < 12; groupIndexone++) {
//                     textName = "text" + groupIndexone;
//                     imgName = "img" + groupIndexone;
//
//                    Field textField = ComplaintEntity.class.getDeclaredField(textName);
//                    textField.setAccessible(true); // 设置字段可访问
//                    Field imgField = ComplaintEntity.class.getDeclaredField(imgName);
//                    imgField.setAccessible(true);
//
//                    if (textField.get(complaintEntity) == null && imgField.get(complaintEntity) == null) {
//                        String prevImgName = "img" + (groupIndexone - 1);
//                        Field prevImgField = complaintEntity.getClass().getDeclaredField(prevImgName);
//                        prevImgField.setAccessible(true);
//                        String prevTextName = "text" + (groupIndexone - 1);
//                        Field prevTextField = complaintEntity.getClass().getDeclaredField(prevTextName);
//                        prevTextField.setAccessible(true);
//                        // 设置当前组字段的值为前一组字段的值
//                        textField.set(complaintEntity, prevTextField.get(complaintEntity));
//                        imgField.set(complaintEntity, prevImgField.get(complaintEntity));
//                        text = (String) textField.get(complaintEntity);
//                        img = (String) imgField.get(complaintEntity);
////                        System.out.println("赋值后的 text 字段值为: " + text);
////                        System.out.println("赋值后的 img 字段值为: " + img);
//                        break;
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace(); // 处理异常
//        }


        // 寻找业务员最后一次提交
        Field lastMatchingField = null;
        Field nextField = null;
        String text = null, img = null;
        Field[] fields = complaintEntity.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);

            try {
                Object value = field.get(complaintEntity);
                if (value != null && value.toString().contains(complaintEntity.getSalesman())) {
                    lastMatchingField = field;
                    if (i < fields.length - 1) {
                        nextField = fields[i + 1];
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        try {
            if (lastMatchingField != null) {
                text = (String) lastMatchingField.get(complaintEntity);
                System.out.println("Value of lastMatchingField: " + text);
            }
            if (nextField != null) {
                img = (String) nextField.get(complaintEntity);
                System.out.println("Value of nextField: " + img);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }



        if (complaintEntity != null) {
            model.addAttribute("id", complaintEntity.getId());
            model.addAttribute("customerName", complaintEntity.getCustomerName());
            model.addAttribute("telephone", complaintEntity.getTelephone());
            model.addAttribute("salesman", complaintEntity.getSalesman());
            model.addAttribute("salespersonname", complaintEntity.getSalespersonname());
            model.addAttribute("completionDate", complaintEntity.getCompletionDate());
            model.addAttribute("softwareVersion", complaintEntity.getSoftwareVersion());
            model.addAttribute("processingAmount", complaintEntity.getProcessingAmount());
            model.addAttribute("complaintUnit", complaintEntity.getComplaintUnit());
            model.addAttribute("complaintOpinions", text);
            model.addAttribute("complaintOpinionsFiles", img);
        }

//        System.out.println("转到修改页面"+model.asMap());

        return "process/complaint/complaintupdatepage";
    }


    //投诉申请单提交 type 14
    @RequestMapping ("/complaintadd")
    public String complaintadd(@RequestParam("filePath") MultipartFile[] filePath , ComplaintEntity complaintEntity, @AuthenticationPrincipal CustomUserDetails userDetails, Model model) throws IOException, ParseException {
        processListMapper.addPersonAndRealName(complaintEntity.getAuditingPerson(), userMapper.selectName(complaintEntity.getAuditingPerson()), complaintEntity.getId(), complaintEntity.getPaymentWay());

        // 解析图片地址
        StringBuilder complaintOpinionsFiles = new StringBuilder();
        String realaddress = null;
        for(MultipartFile file:filePath){
            realaddress= fileService.transfer(file);
            complaintOpinionsFiles.append(realaddress).append("|");
            // 在控制台输出文件的实际存储地址
//            System.out.println("File " + file.getOriginalFilename() + " stored at: " + realaddress);
        }
        if (realaddress != null){
            if (complaintOpinionsFiles.length() > 0) {
                complaintOpinionsFiles.setLength(complaintOpinionsFiles.length() - 1); // 去掉最后一个"|"
            }
            complaintEntity.setComplaintOpinionsFiles(complaintOpinionsFiles.toString());  // 添加地址
        }

        // 获取当前时间 格式化当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedTime = currentTime.format(formatter);

        String opinions = complaintEntity.getComplaintOpinions();
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        String complaintOpinions =formattedTime+ "," + ru.getPositionName()+userDetails.getRealName() + "接到的客户反馈: " + opinions;
        complaintEntity.setComplaintOpinions(complaintOpinions);
        complaintEntity.setPositionName(ru.getPositionName());
        complaintEntity.setDepartmentName(ru.getDepartmentName());
        complaintMapper.complaintEntityInsert(complaintEntity);

        // 时间轴相关 在创建单据时插入第一个审核人
        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);
        String text1 = formDateTime + "; " + userMapper.selectName(complaintEntity.getAuditingPerson());
        processStatusMapper.statusInsert(complaintEntity.getId(),text1);


        //为了记录未读消息提醒(messageType = "1")
        List hasBeenReadModelList = new ArrayList<>();
        HasBeenReadModel hasBeenReadModel  = new HasBeenReadModel();
        hasBeenReadModel.setUsername(complaintEntity.getAuditingPerson());
        hasBeenReadModel.setMessageId(complaintEntity.getId());
        hasBeenReadModel.setMessageType("1");
        hasBeenReadModelList.add(hasBeenReadModel);
        hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);

//        System.out.println(" complaintEntity = " + complaintEntity + ", userDetails = " + userDetails + ", model = " + model);


        return  "process/processadd";
    }



    //投诉单修改提交
    @RequestMapping ("/complaintUpdate")
    @ResponseBody
    public String complaintUpdate(@RequestParam("imagePath") String[] imagePath , @RequestParam("filePath") MultipartFile[] filePath , ComplaintEntity complaintEntity, @AuthenticationPrincipal CustomUserDetails userDetails, Model model) throws IOException, ParseException {

        System.out.println("263"+complaintEntity);

        // 获取数据库已有数据
        ComplaintEntity ce = complaintMapper.selectById(complaintEntity.getId());
//        System.out.println("225 ce = " + ce);

        // 解析图片地址
        StringBuilder complaintOpinionsFiles = new StringBuilder();
        String realaddress = null;
        for(MultipartFile file:filePath){
            realaddress= fileService.transfer(file);
            complaintOpinionsFiles.append(realaddress).append("|");
            // 在控制台输出文件的实际存储地址
//            System.out.println("236 File " + file.getOriginalFilename() + " stored at: " + realaddress);
        }


        // 获取当前时间 格式化当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedTime = currentTime.format(formatter);

        String opinions = complaintEntity.getComplaintOpinions();
//        System.out.println("256新的修改: " + opinions);
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        String complaintOpinions =formattedTime + "," + ru.getPositionName()+userDetails.getRealName()+ "接到的客户反馈: " + opinions;
//        System.out.println("259修改后的数据: "+complaintOpinions);


        // 寻找一组空字段text与img
        String complaintOpinionsFilesImg = null;
        String originalValueForNextField = null;
        try {
            if (ce.getText1() == null && ce.getImg1() == null) {
                // 如果text1和img1都为空，直接修改原值
                ce.setComplaintOpinions(complaintOpinions);

                // 获取数据库中已保存的值
                String complaintFiles = ce.getComplaintOpinionsFiles();
                // 判断是否有值 作删除操作
                if (imagePath != null){
                    try {
                        // 直接解析JSON字符串为数组
                        List<String> imagePaths = Arrays.asList(imagePath);

                        // 遍历图片路径数组
                        for (String path : imagePaths) {
                            System.out.println("Image path: " + path);
                            // 删除ComplaintOpinionsFiles中包含path的路径
                            complaintFiles = complaintFiles.replace(path + "|", ""); // 添加"|"
                            complaintFiles = complaintFiles.replace("|" + path, ""); // 添加"|"
                            complaintFiles = complaintFiles.replace(path, ""); // 避免路径出现在开头或结尾的情况
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("删除图片后的数据" + complaintFiles);

                }

                if (realaddress != null){
                    if (complaintOpinionsFiles.length() > 0) {
                        complaintOpinionsFiles.setLength(complaintOpinionsFiles.length() - 1); // 去掉最后一个"|"
                        if (complaintFiles != null){
                            String com = complaintOpinionsFiles.toString();  // 新传递的图片地址
                            ce.setComplaintOpinionsFiles(complaintFiles+"|"+com);  // 如数据库有值则合成新的地址
                        }else {
                            ce.setComplaintOpinionsFiles(complaintOpinionsFiles.toString());  // 无值则把新的图片路径放进去
                        }
                    }
                }else {
                    ce.setComplaintOpinionsFiles(complaintFiles);  // 把原有地址再放回去
                }

                System.out.println("删除+新增: "+ ce.getComplaintOpinionsFiles());

            } else {

                Field lastMatchingField = null;
                Field nextField = null;

                Field[] fields = ce.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    field.setAccessible(true);

                    try {
                        Object value = field.get(ce);
                        if (value != null && value.toString().contains(ce.getSalesman())) {
                            lastMatchingField = field;
                            if (i < fields.length - 1) {
                                nextField = fields[i + 1];
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

                if (lastMatchingField != null) {
                    try {
                        lastMatchingField.setAccessible(true);
                        lastMatchingField.set(ce, complaintOpinions);
                        // 获取数据库中已保存的值 原先的值
                        originalValueForNextField = (String) nextField.get(ce);
                        System.out.println("获取原先的值"+originalValueForNextField);

                        // 判断是否有值
                        if (imagePath != null){
                            try {
                                // 直接解析JSON字符串为数组
                                List<String> imagePaths = Arrays.asList(imagePath);

                                // 遍历图片路径数组
                                for (String path : imagePaths) {
                                    System.out.println("Image path: " + path);
                                    // 删除ComplaintOpinionsFiles中包含path的路径
                                    originalValueForNextField = originalValueForNextField.replace(path + "|", ""); // 添加"|"
                                    originalValueForNextField = originalValueForNextField.replace("|" + path, ""); // 添加"|"
                                    originalValueForNextField = originalValueForNextField.replace(path, ""); // 避免路径出现在开头或结尾的情况
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println("383 删除图片后的数据" + originalValueForNextField);

                        }

                        if (realaddress != null){
                            if (complaintOpinionsFiles.length() > 0) {
                                complaintOpinionsFiles.setLength(complaintOpinionsFiles.length() - 1); // 去掉最后一个"|"
                                if (originalValueForNextField != null){
                                    String com = complaintOpinionsFiles.toString();  // 新传递的图片地址
                                    complaintOpinionsFilesImg = originalValueForNextField+"|"+com;  // 如数据库有值则合成新的地址
                                }else {
                                    complaintOpinionsFilesImg =complaintOpinionsFiles.toString();  // 无值则把新的图片路径放进去
                                }
                            }
                        }else {
                            complaintOpinionsFilesImg = originalValueForNextField;  // 把原有地址再放回去
                        }

                        System.out.println("401 删除+新增: "+ complaintOpinionsFilesImg);

                        // 修改下一个字段的值
                        nextField.setAccessible(true);
                        nextField.set(ce, complaintOpinionsFilesImg);

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("未找到符合条件的字段！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }
        ce.setCustomerName(complaintEntity.getCustomerName());
        ce.setTelephone(complaintEntity.getTelephone());
        ce.setCompletionDate(complaintEntity.getCompletionDate());
        ce.setSoftwareVersion(complaintEntity.getSoftwareVersion());
        ce.setProcessingAmount(complaintEntity.getProcessingAmount());
        ce.setComplaintUnit(complaintEntity.getComplaintUnit());
        ce.setSalespersonname(complaintEntity.getSalespersonname());

        System.out.println("361"+ce);

        //驳回修改提交
        complaintMapper.rejectUpdateComplaint(ce);

        // process表中需要修改的审核人
        String auditingPerson = complaintEntity.getAuditingPerson();

        // 已完成审核显示(只限投诉单据)
        ProcessEntity pe = processListMapper.selectById(complaintEntity.getId());
        String completeReview = pe.getCompleteReview();
        if (completeReview != null){

            // 判断 completeReview 中是否包含 auditingPerson 的值并删除
            if (completeReview.contains(auditingPerson)) {
                completeReview = completeReview.replace(auditingPerson + "|", "").replace("|" + auditingPerson, "").replace(auditingPerson, "");
            }
            completeReview = completeReview +"|"+userDetails.getUsername();
        }else {
            completeReview = userDetails.getUsername();
        }
//        System.out.println("301更新后的 completeReview 值为: " + completeReview);


        // 修改的状态审核人
        String auditingPersonRealName = complaintMapper.selectByName(auditingPerson);
//        System.out.println("审核人: " + auditingPerson +" , "+ "审核人: " + auditingPersonRealName);
        // 每提交一次修改一次实现循环
        complaintMapper.updateAuditerStatus(complaintEntity.getId(),auditingPerson,auditingPersonRealName,completeReview);


        /*=====================时间轴相关部分=======================*/

        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);

        String textNameValue = formDateTime + "; " + userMapper.selectName(complaintEntity.getAuditingPerson());
        String statusNameValue = "3";
        //根据ID查询投诉单据
        StatusEntity statusEntity = processStatusMapper.selectById(complaintEntity.getId());
        // 寻找一组空字段text与img进行插入
        int groupIndexone = 2;
        String textName = "text" + groupIndexone ;
        String statusName = "status" + groupIndexone;

        try {
            while (true) {
                Field textField = StatusEntity.class.getDeclaredField(textName);
                textField.setAccessible(true); // 设置字段可访问
                Field statusField = StatusEntity.class.getDeclaredField(statusName);
                statusField.setAccessible(true);

                if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(statusEntity, textNameValue);
                    statusField.set(statusEntity, statusNameValue);

                    // 找到空字段并插入后，修改上一个status字段的值为"1"
                    String prevStatusName = "status" + (groupIndexone-1);
                    Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                    prevStatusField.setAccessible(true);
                    if (prevStatusField.get(statusEntity) != null) {
                        prevStatusField.set(statusEntity, "1");
                    }

                    break; // 找到空字段并插入后结束循环
                }

                groupIndexone++;
                textName = "text" + groupIndexone;
                statusName = "status" + groupIndexone;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        processStatusMapper.updateStatus(statusEntity, complaintEntity.getId());

        /*=====================时间轴相关部分end=======================*/


        //为了记录未读消息提醒(messageType = "1")
        List hasBeenReadModelList = new ArrayList<>();
        HasBeenReadModel hasBeenReadModel  = new HasBeenReadModel();
        hasBeenReadModel.setUsername(complaintEntity.getAuditingPerson());
        hasBeenReadModel.setMessageId(complaintEntity.getId());
        hasBeenReadModel.setMessageType("1");
        hasBeenReadModelList.add(hasBeenReadModel);
        hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);


        return  "process/myprocess";
    }







    //下一步添加建议
    @RequestMapping("/reason")
    @ResponseBody
    public String reason(@AuthenticationPrincipal CustomUserDetails userDetails, @Param("copyPersons")String copyPersons,@RequestParam("auditingperson") String auditingperson, @RequestParam("id") String id, @RequestParam("reason") String reason, @RequestParam(value = "file", required = false) MultipartFile[] files) throws IOException {
//        System.out.println("529 copyPersons = " + copyPersons);
        // 解析图片地址
        StringBuilder complaintOpinionsFiles = new StringBuilder();
        String realaddress = null;
        if (files != null) {
            for (MultipartFile file : files) {
                realaddress = fileService.transfer(file);
                if (realaddress != null) {
                    complaintOpinionsFiles.append(realaddress).append("|");
                    // 在控制台输出文件的实际存储地址
//                    System.out.println("File " + file.getOriginalFilename() + " stored at: " + realaddress);
                }
            }
            if (complaintOpinionsFiles.length() > 0) {
                complaintOpinionsFiles.setLength(complaintOpinionsFiles.length() - 1); // 去掉最后一个"|"
            }
        }
        String imgValue = complaintOpinionsFiles.toString();
//        System.out.println("图片地址：" + imgValue);

        // 获取当前时间 格式化当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedTime = currentTime.format(formatter);

        //获取职位信息
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        String textValue =formattedTime+ "," + ru.getPositionName()+userDetails.getRealName()+ "的处理结果: " + reason;  //拼接职位意见
//        System.out.println("text字段" + textValue);

        //根据ID查询投诉单据
        ComplaintEntity complaintEntity = complaintMapper.selectById(id);
//        System.out.println("查询到的数据" + complaintEntity);

        // 寻找一组空字段text与img进行插入
        int groupIndex = 1;
        String textFieldName = "text" + groupIndex;
        String imgFieldName = "img" + groupIndex;

        try {
            while (true) {
                Field textField = ComplaintEntity.class.getDeclaredField(textFieldName);
                textField.setAccessible(true); // 设置字段可访问
                Field imgField = ComplaintEntity.class.getDeclaredField(imgFieldName);
                imgField.setAccessible(true);

                if (textField.get(complaintEntity) == null && imgField.get(complaintEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(complaintEntity, textValue);
                    imgField.set(complaintEntity, imgValue);
                    break; // 找到空字段并插入后结束循环
                }

                groupIndex++;
                textFieldName = "text" + groupIndex;
                imgFieldName = "img" + groupIndex;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        complaintMapper.updateComplaint(complaintEntity);

        /*=====================时间轴相关部分=======================*/

        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formDateTime = currentTime.format(formDate);

        String textNameValue = formDateTime + "; " + userMapper.selectName(auditingperson);
        String statusNameValue = "3";
        //根据ID查询投诉单据
        StatusEntity statusEntity = processStatusMapper.selectById(id);
        // 寻找一组空字段text与img进行插入
        int groupIndexone = 2;
        String textName = "text" + groupIndexone ;
        String statusName = "status" + groupIndexone;

        try {
            while (true) {
                Field textField = StatusEntity.class.getDeclaredField(textName);
                textField.setAccessible(true); // 设置字段可访问
                Field statusField = StatusEntity.class.getDeclaredField(statusName);
                statusField.setAccessible(true);

                if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(statusEntity, textNameValue);
                    statusField.set(statusEntity, statusNameValue);

                    // 找到空字段并插入后，修改上一个status字段的值为"1"
                    String prevStatusName = "status" + (groupIndexone-1);
                    Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                    prevStatusField.setAccessible(true);
                    if (prevStatusField.get(statusEntity) != null) {
                        prevStatusField.set(statusEntity, "1");
                    }

                    break; // 找到空字段并插入后结束循环
                }

                groupIndexone++;
                textName = "text" + groupIndexone;
                statusName = "status" + groupIndexone;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        processStatusMapper.updateStatus(statusEntity, id);



        // 已完成审核显示(只限投诉单据)
        ProcessEntity pe = processListMapper.selectById(id);
        String completeReview = pe.getCompleteReview();
        if (completeReview != null){
            // 判断 completeReview 中是否包含 auditingPerson 的值并删除
            if (completeReview.contains(auditingperson)) {
                completeReview = completeReview.replace(auditingperson + "|", "").replace("|" + auditingperson, "").replace(auditingperson, "");
            }
            completeReview = completeReview +"|"+userDetails.getUsername();
        }else {
            completeReview = userDetails.getUsername();
        }
//        System.out.println("415更新后的 completeReview 值为: " + completeReview);

        // 修改的状态审核人
        String auditingPersonRealName = complaintMapper.selectByName(auditingperson);
        complaintMapper.updateAuditerStatus(id,auditingperson,auditingPersonRealName,completeReview);
//        System.out.println("382修改的状态审核人执行了");

        //为了记录未读消息提醒(messageType = "1")
        List hasBeenReadModelList = new ArrayList<>();
        HasBeenReadModel hasBeenReadModel  = new HasBeenReadModel();
        hasBeenReadModel.setUsername(auditingperson);
        hasBeenReadModel.setMessageId(id);
        hasBeenReadModel.setMessageType("1");
        hasBeenReadModelList.add(hasBeenReadModel);
        hasBeenReadMapper.addHasBeenReads(hasBeenReadModelList);

        //将抄送的人给加入到表中
        JSONArray ja=JSONArray.parseArray(copyPersons);
        List<String> copyPersonsLs=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            copyPersonsLs.add(jsonObject.getString("value"));
        }

        if(copyPersonsLs.size()>0){
            processListMapper.upsertCopy(copyPersonsLs,id);

            //为了记录未读消息提醒(messageType = "3")
            List hasBeenReadModelListCP = new ArrayList<>();
            for (String cp:copyPersonsLs){
                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                hasBeenReadModelCP.setUsername(cp);
                hasBeenReadModelCP.setMessageId(id);
                hasBeenReadModelCP.setMessageType("3");
                hasBeenReadModelListCP.add(hasBeenReadModelCP);
            }
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
        }



        return "Success";
    }


        /**
         * 修改投诉单图片修改
         * @param requestData
         * @return
         */
    @PostMapping("/complaintDeletedImagePath")
    @ResponseBody
    public String complaintDeletedImagePath(@RequestBody Map<String, String> requestData) {
        String ImagePath = requestData.get("ImagePath");
        String id = requestData.get("id");
        System.out.println("需要删除的图片" + ImagePath);
        ComplaintEntity ce = complaintMapper.selectById(id);

        // 寻找业务员最后一次提交
        Field nextField = null;
        String img = null;
        String stringValue = null;
        Field[] fields = ce.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);

            try {
                Object value = field.get(ce);
                if (value instanceof String) {
                    stringValue = (String) value;
                    if (stringValue.contains(ImagePath)) {
                        stringValue = stringValue.replaceAll(ImagePath, ""); // 删除指定数据
                        field.set(ce, stringValue);
                    }
                }
                if (value != null && value.toString().contains(ce.getSalesman())) {
                    if (i < fields.length - 1) {
                        nextField = fields[i + 1];
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        try {
            if (nextField != null) {
                img = (String) nextField.get(ce);
                System.out.println("681 imgNextField: " + img);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


//        String[] fileAddresses = ce.getComplaintOpinionsFiles().split("\\|");
//        System.out.println("查询到的图片数据"+Arrays.toString(fileAddresses));
//        List<String> uniqueFileAddresses = new ArrayList<>(Arrays.asList(fileAddresses));
//        uniqueFileAddresses.remove(ImagePath);
//        String result = String.join("|", uniqueFileAddresses);
//        System.out.println("拼接"+ result);
//
//        complaintMapper.updateComplaintPathAndId(id, result);


        return "200";
    }


    /**
     * 点击完成按钮修改状态
     * @param requestData
     * @return
     */
    @PostMapping("/overComplaint")
    @ResponseBody
    public String overComplaint(@AuthenticationPrincipal CustomUserDetails userDetails,@RequestBody Map<String, String> requestData) {
        String id = requestData.get("id");
        String finalFollowUp = requestData.get("finalFollowUp");
        String copyPersons = requestData.get("copyPersons");
//        System.out.println("752"+copyPersons);
        // 图片的值但是目前用不到
        // String imgValue ;
        //获取职位信息
        ReturnUser ru = userMapper.findPositonDepartmentNameByName(userDetails.getUsername());
        String textValue = ru.getPositionName()+userDetails.getRealName()+ "的最终处理结果: " + finalFollowUp;  //拼接职位意见
        //根据ID查询投诉单据
        ComplaintEntity complaintEntity = complaintMapper.selectById(id);
        // 寻找一组空字段text与img进行插入
        int groupIndex = 1;
        String textFieldName = "text" + groupIndex;
        String imgFieldName = "img" + groupIndex;

        try {
            while (true) {
                Field textField = ComplaintEntity.class.getDeclaredField(textFieldName);
                textField.setAccessible(true); // 设置字段可访问
                Field imgField = ComplaintEntity.class.getDeclaredField(imgFieldName);
                imgField.setAccessible(true);

                if (textField.get(complaintEntity) == null && imgField.get(complaintEntity) == null) {
                    // 将获取到的textValue和imgValue插入到一组空字段中
                    textField.set(complaintEntity, textValue);
//                    imgField.set(complaintEntity, imgValue);
                    break; // 找到空字段并插入后结束循环
                }

                groupIndex++;
                textFieldName = "text" + groupIndex;
                imgFieldName = "img" + groupIndex;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }
        // 保存更新后的单据
        complaintMapper.updateComplaint(complaintEntity);


        /*=====================时间轴相关部分(点击完成)=======================*/
//        LocalDateTime currentTime = LocalDateTime.now();
//        DateTimeFormatter formDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//        String formDateTime = currentTime.format(formDate);
//
//        String textNameValue = formDateTime + "; " + userMapper.selectName(complaintEntity.getAuditingPerson());
//        String statusNameValue = "1";
        //根据ID查询投诉单据
        StatusEntity statusEntity = processStatusMapper.selectById(complaintEntity.getId());
        // 寻找一组空字段text与img进行插入
        int groupIndexone = 2;
        String textName = "text" + groupIndexone ;
        String statusName = "status" + groupIndexone;

        try {
            while (true) {
                Field textField = StatusEntity.class.getDeclaredField(textName);
                textField.setAccessible(true); // 设置字段可访问
                Field statusField = StatusEntity.class.getDeclaredField(statusName);
                statusField.setAccessible(true);

                if (textField.get(statusEntity) == null && statusField.get(statusEntity) == null) {
//                    // 将获取到的textValue和imgValue插入到一组空字段中
//                    textField.set(statusEntity, textNameValue);
//                    statusField.set(statusEntity, statusNameValue);

                    // 找到空字段并插入后，修改上一个status字段的值为"1"
                    String prevStatusName = "status" + (groupIndexone-1);
                    Field prevStatusField = StatusEntity.class.getDeclaredField(prevStatusName);
                    prevStatusField.setAccessible(true);
                    if (prevStatusField.get(statusEntity) != null) {
                        prevStatusField.set(statusEntity, "1");
                    }

                    break; // 找到空字段并插入后结束循环
                }

                groupIndexone++;
                textName = "text" + groupIndexone;
                statusName = "status" + groupIndexone;
            }
        } catch (Exception e) {
            e.printStackTrace(); // 处理异常
        }

        // 保存更新后的单据
        processStatusMapper.updateStatus(statusEntity, complaintEntity.getId());

        /*=====================时间轴相关部分(点击完成)end=======================*/


        // 修改状态为完成状态
        String auditingPersonRealName = userDetails.getRealName();
        complaintMapper.overComplaintId(id,auditingPersonRealName);

        //将抄送的人给加入到表中
        JSONArray ja=JSONArray.parseArray(copyPersons);
        List<String> copyPersonsLs=new ArrayList<>();
        for(int i=0;i<ja.size();i++){
            JSONObject jsonObject =ja.getJSONObject(i);
            copyPersonsLs.add(jsonObject.getString("value"));
        }

        if(copyPersonsLs.size()>0){
            processListMapper.upsertCopy(copyPersonsLs,id);

            //为了记录未读消息提醒(messageType = "3")
            List hasBeenReadModelListCP = new ArrayList<>();
            for (String cp:copyPersonsLs){
                HasBeenReadModel hasBeenReadModelCP  = new HasBeenReadModel();
                hasBeenReadModelCP.setUsername(cp);
                hasBeenReadModelCP.setMessageId(id);
                hasBeenReadModelCP.setMessageType("3");
                hasBeenReadModelListCP.add(hasBeenReadModelCP);
            }
            hasBeenReadMapper.addHasBeenReads(hasBeenReadModelListCP);
        }


        return "Success";
    }


    private class complaintEntity {
    }
}